<?php

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Api\BaseController;
use App\Services\Business\Models\Tag;
use App\Services\Business\Models\TagCategory;
use App\Services\Business\Models\Taggables;
use App\Services\Business\Services\TagCategoryService;
use App\Services\Business\Interfaces\TagCategoryServiceInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class TagController extends BaseController
{
    /**
     * @var TagCategoryService
     */
    protected $tagCategoryService;

    public function __construct(
        TagCategoryServiceInterface $tagCategoryService
    )
    {
        $this->tagCategoryService = $tagCategoryService;
    }


    public function index(Request $request)
    {


        $cid = (int)$request->input('cid');
        $keywords = (string)$request->input('keywords');
        $tags = Tag::query()
            ->select([
                'id', 'name', 'category_id'
            ])
            ->when($cid, function ($query) use ($cid) {
                $query->where('category_id', '=', $cid);
            })
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('name', 'like', '%' . $keywords . '%');
            })
            ->orderByDesc('created_at')
            ->paginate($request->input('size', 10));
        return $this->successData(compact('tags'));
    }

    public function detail(Request $request, $id)
    {

        $page = $request->input('page', 1);
        $size = $request->input('size', 10);


        $tag = Tag::query()->with(['category'])->where('id', $id)->firstOrFail();
        $tags = Tag::query()
            ->where('category_id', $tag->category_id)
            ->forPage($page, $size)
            ->get()
            ->toArray();
        return $this->successData(compact('tag', 'tags'));


    }

    public function resources(Request $request)
    {
        $tagId = $request->input('tag_id');
        $type = $request->input('type');
        $size = $request->input('size');

        $resourceIds = Taggables::query()
            ->where('tag_id', $tagId)
            ->where('taggable_type', 'App\Services\Business\Models\\' . ucfirst($type))
            ->pluck('taggable_id');

        $model = 'App\Services\Business\Models\\' . ucfirst($type);
        $model = new $model();
        $resources = $model::query()
            ->with(['user'])
            ->whereIn('id', $resourceIds ?? [])
            ->paginate($size);
        return $this->successData(compact('resources'));

    }

    public function category()
    {
        $categories = TagCategory::query()->select(['id', 'name'])->get();
        return $this->data($categories);

    }

    public function store(Request $request)
    {
        $name = mb_substr(strip_tags($request->input('name', '')), 0, 255);
        $tagCategoryId = (int)$request->input('category_id');
        if (Tag::query()->where('name', $name)->exists()) {
            return $this->error(__('标签已存在'));
        }
        $tag = Tag::create([
            'name' => $name,
            'category_id' => $tagCategoryId,
        ]);

        return $this->successData($tag);
    }

    public function update(Request $request, $id)
    {
        $name = $request->input('name');
        $cid = (int)$request->input('category_id');
        if (!$name || !$cid) {
            return $this->error(__('参数错误'));
        }

        $tag = Tag::query()->where('id', $id)->firstOrFail();

        if (Tag::query()->where('name', $name)->where('id', '<>', $id)->exists()) {
            return $this->error(__('标签已存在'));
        }

        $tag->fill(['name' => $name, 'category_id' => $cid])->save();

        return $this->success(__('标签更新成功'));
    }


    public function delete($id)
    {


        if (DB::table('taggables')->where('tag_id', $id)->exists()) {
            return $this->error(__('标签已关联资源，无法删除'));
        }
        Tag::destroy($id);
        return $this->success(__('标签删除成功'));
    }
    public function sync(Request $request, string $type, int $id)
    {
        $modal = 'App\Services\Business\Models\\' . ucfirst($type);
        $modal = new $modal;
        $resource = $modal::find($id);
        $ids = (array)$request->input("ids", []);
        if (empty($id)) {
            return $this->error(__('参数错误'));
        }

        $resource->tags()->sync($ids);

        return $this->success(__('绑定标签成功'));
    }


}